package com.dst.util;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUtils {
    private static Properties p=new Properties();
    private static  ThreadLocal<Connection> tl=new ThreadLocal<>();
    static {
        try (
                InputStream is=JdbcUtils.class.getResourceAsStream("/jdbc.properties");
                ){
            p.load(is);
            Class.forName(p.getProperty("drive"));
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    public static Connection getConnection(){
        Connection conn=tl.get();
        try {
            if(conn==null){
                String url=p.getProperty("url");
                String username=p.getProperty("username");
                String password=p.getProperty("password");
                conn= DriverManager.getConnection(url, username, password);
                tl.set(conn);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  conn;
    }
    public static  void close(ResultSet rs, PreparedStatement pstmt ,Connection conn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(pstmt!=null){
            try {
                pstmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
